<?php
namespace gnomephp;

use gnomephp\mvc\Router;

/**
 * 
 * Url class for handling url specific things, it can find the real link to a controller.method (args) and can also link to public resources.
 * @author peec
 *
 */
class Url{
	/**
	 * Keeps track of links that are found, caching variable for Url method linkTo.
	 * @var array
	 */
	static public $linkCache = array();
	
	
	/**
	 * 
	 * Links to a specific resource in the public/ folder of the application.
	 * Use this to link to CSS/Javascript and images in the View.
	 * @param string $resource The resource relative to the public/ dir. Eg. "css/main.css"
	 * @param string $prefix If you want to prefix the resource, this should be defined.
	 */
	public function link($resource, $prefix=null){
		if (!isset($_SERVER['PATH_INFO']))$path = '';
		else $path = $_SERVER['PATH_INFO'];
		$exp = explode('/', $_SERVER['SCRIPT_NAME']);
		
		$scriptName = $exp[count($exp)-1];
		
		return str_replace('/'.$scriptName, '', substr($_SERVER['PHP_SELF'], 0, strlen($_SERVER['PHP_SELF'])-strlen($path))).'/'.$prefix.$resource;
	}
	
	
	/**
	 * 
	 * Finds the link and returns the link to a specific controller/method/args... based on the router configuration.
	 * 
	 * @param string $controller The controller name.
	 * @param string $method The method name.
	 * @param array $args array of arguments if any.
	 * @throws UrlException
	 */
	public function linkTo($name, $args=null){
		if ($url = \gnomephp\mvc\Dispatcher::$map->generate($name, $args)){
			return self::link(substr($url, 1), (!Configuration::get('application', 'remove_php_script') ? 'index.php/' : null));
		}else throw new UrlException("There are no routes defined for route $name. ");
	}
	
	/**
	 * 
	 * Checks if a link is active, you will have to define controller / method, based on the router configuration, this method can check if it's currently active.
	 * @param string $name The name of the route.
	 */
	public function linkIsActive($name){
		return $name == \gnomephp\mvc\Dispatcher::$activeRoute;
	}
	
	
}